package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 一个socket，理解为一个电话
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            socket = new Socket("192.168.145.1",9999);
            System.out.println("连接服务端。");
        } catch (IOException e) {
           e.printStackTrace();
        }
    }

    public void start(){
        ServerHandler serverHandler = new ServerHandler();
        Thread t = new Thread(serverHandler);
        t.start();
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输入昵称：");
                String nickName = scanner.nextLine();
                if (nickName.isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickName);
                    break;
                }
            }
            while (true){
                String line = scanner.nextLine();
                if ("exist".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
            }
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
